<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :md="6" :sm="24">
            <a-form-item label="报告名称">
              <j-dict-select-tag
                type="list"
                v-model="queryParam.reportId"
                dictCode="user_reports,report_name,id"
                placeholder="请选择报告"
                @input="onReportChange"
              />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="日期">
              <a-range-picker
                style="width: 210px"
                v-model="queryParam.createTimeRange"
                format="YYYY-MM-DD"
                :placeholder="['开始时间', '结束时间']"
                @change="onDateChange"
              />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="槽号">
              <a-select show-search placeholder="请选择槽号" v-model="queryParam.slotNo">
                <a-select-option v-for="item in slotIdList" :key="item" :value="item">
                  {{ item }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
            <a-col :md="6" :sm="24">
              <a-button type="primary" style="left: 10px" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset1" icon="reload" style="margin-left: 8px; left: 10px"
                >重置</a-button
              >
              <!-- <a-button type="primary" style="margin-left: 8px; left: 10px" @click="loadData(1)" icon="reload">刷新</a-button> -->
            </a-col>
          </span>
        </a-row>
      </a-form>
    </div>
    <a-table
      ref="table"
      size="middle"
      bordered
      :columns="columns"
      :dataSource="tbList"
      :pagination="ipagination"
      @change="handleTableChange"
      class="j-table-force-nowrap"
    >
    </a-table>
    <j-modal
      title="待执行确认"
      :width="800"
      :visible="visible"
      :draggable="true"
      :confirmLoading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
      okText="任务执行"
      cancelText="关闭"
    >
      <a-spin :spinning="confirmLoading">
        缺失的日期：
        {{ dateUntreated }}
      </a-spin>
      <br />
      <a-alert
        message="【任务执行】会对缺失的日期的报告数据进行生成操作；如若缺失日期过多，该执行过程时间会过长，请稍微刷新数据查看！"
        type="info"
        show-icon
      />
    </j-modal>
  </a-card>
</template> 

<script>
import moment from 'moment'
import { deleteAction, getAction, postAction, downFile, getFileAccessHttpUrl } from '@/api/manage'
import JMultiSelectTag from '@/components/dict/JMultiSelectTag'
export default {
  name: 'UserReportsHistory',
  components: { JMultiSelectTag },
  data() {
    return {
      title: '报告查询',
      width: 800,
      visible: false,
      selectionRow: {},
      dateUntreated: [],
      slotIdList: [],
      model: {
        reportId: '',
        calcDate: '', //计算时间
      },
      selectDate: '', // =计算时间 格式 （yyyy-MM-dd）
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      tbList: [], //
      confirmLoading: false,
      loading: false,
      columns: [],
      queryParam: {
        reportId: '',
        createTimeRange: [],
        slotNo: '',
      },
      url: {
        exportXlsUrl: '/userReports/userReports/exportXls2',
        queryById: '/userReports/userReports/queryById',
        execute: 'sys/quartzJob/execute2',
      },
    }
  },
  created() {
    this.initDate()
  },
  methods: {
    loadDataSlot(reportId) {
      var that = this
      that.slotIdList = []
      that.queryParam.slotNo = ''
      getAction('/userReports/userReports/queryUserReportsRowByMainId', { id: reportId })
        .then((res) => {
          if (res.success) {
            var dataSource = res.result
            for (let i = 0; i < dataSource.length; i++) {
              that.slotIdList.push(dataSource[i].slotName)
            }
          }
        })
        .finally(() => {
          that.loading = false
        })
    },
    searchQuery() {
      if (!this.queryParam['reportId']) {
        this.$message.error('请选择报告')
        return
      }
      if (this.queryParam.createTimeRange.length == 0) {
        this.$message.error('请选择日期')
        return
      }

      this.searchDate()
      this.loadData(1)
    },
    searchReset1() {
      this.queryParam.slotNo = ''
      this.queryParam.reportId = ''
      this.initDate()
      this.tbList = []
      //this.loadData(1)
    },
    initDate() {
      let date = new Date()
      var year = new Date().getFullYear()
      var month = new Date().getMonth()
      let date2 = new Date(year, month, 1)
      this.date2 = moment(date2).format('YYYY-MM-DD')
      this.date = moment(date).format('YYYY-MM-DD')
      this.queryParam.createTimeRange = [moment(this.date2), moment(this.date)]
      this.queryParam.createTime_begin = this.date2
      this.queryParam.createTime_end = this.date
    },

    close() {
      this.visible = false
    },
    searchDate() {
      var that = this
      if (!this.queryParam['reportId']) {
        that.$message.error('请选择报告')
        return
      }
      var param = Object.assign({}, this.queryParam)
      param['id'] = param.reportId
      getAction(`/userReports/userReports/hisotryDays?slotNo=${param.slotNo}`, param).then((res) => {
        this.confirmLoading = false
        if (res.success) {
          that.dateUntreated = res.result
          if (that.dateUntreated.length > 0) {
            that.visible = true
          }
        } else {
          that.$message.error(res.message)
        }
      })
    },
    loadData(arg) {
      var that = this
      that.confirmLoading = true
      if (arg === 1) {
        this.ipagination.current = 1
      }
      let sqp = {}
      var param = Object.assign(sqp, this.queryParam)
      param['id'] = param.reportId
      param.pageNo = that.ipagination.current
      param.pageSize = that.ipagination.pageSize
      getAction(`/userReports/userReports/hisotryPageList?slotNo=${param.slotNo}`, param).then((res) => {
        this.confirmLoading = false
        if (res.success) {
          var data = res.result
          var fileNames = data.records[0].userReportsFieldList //列名用 自定义列 （序号排序）
          that.columns = [
            {
              title: '槽号',
              align: 'center',
              dataIndex: 'slot',
            },
            {
              title: '日期',
              align: 'center',
              dataIndex: 'calc_date',
            },
          ]
          that.tbList = []
          for (let i = 0; i < fileNames.length; i++) {
            const element = fileNames[i]
            that.columns.push({
              title: element.fieldName,
              dataIndex: element.tableColumn,
              align: 'center',
            })
          }
          that.tbList = data.records.slice(1)
          that.ipagination.total = res.result.total
        } else {
          that.$message.error(res.message)
        }
      })
    },
    handleOk() {
      var that = this
      //立即执行定时任务
      this.$confirm({
        title: '确认提示',
        content: '是否立即执行任务?',
        onOk: function () {
          getAction(that.url.execute, {
            reportId: that.queryParam.reportId,
            dateUntreated: JSON.stringify(that.dateUntreated),
          }).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.dateUntreated = []
              that.visible = false
            } else {
              that.$message.warning(res.message)
            }
          })
        },
      })
    },
    handleCancel() {
      this.close()
    },
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      // console.log(pagination)
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.loadData()
    },
    onDateChange: function (value, dateString) {
      console.log(dateString[0], dateString[1])
      this.queryParam.createTime_begin = dateString[0]
      this.queryParam.createTime_end = dateString[1]
    },
    onReportChange() {
      this.loadDataSlot(this.queryParam.reportId)
    },
  },
}
</script>

<style scoped>
</style>